<?php
/**
 * 网页抢楼模块微站定义
 *
 * @author junsion
 * @url http://bbs.we7.cc/
 */
defined('IN_IA') or exit('Access Denied');
define('OD_ROOT', IA_ROOT . '/addons/junsion_netlottery');
class Junsion_netlotteryModuleSite extends WeModuleSite {

	public function doWebIndex() {
		//这个操作被定义用来呈现 管理中心导航菜单
		global $_W,$_GPC;
		$op = $_GPC['op'] ? $_GPC['op'] : 'list';
		$id = $_GPC['rid'];
		if ($op == 'post'){
			if (checksubmit('submit')){
				$prizeranks = $_GPC['prizerank'];
				foreach ($prizeranks as $key => $value) {
					if (empty($value)) continue;
					$prize[] = array('prizerank'=>$value,'prizename'=>$_GPC['prizename'][$key],'prizethumb'=>$_GPC['prizethumb'][$key],'prizedesc'=>$_GPC['prizedesc'][$key]);
				}
				$data = array(
					'weid'=>$_W['uniacid'],
					'title'=>$_GPC['title'],
					'starttime'=>strtotime($_GPC['date']['start']),
					'endtime'=>strtotime($_GPC['date']['end']),
					'pictrues'=>serialize($_GPC['pictrues']),
					'stitle'=>$_GPC['stitle'],
					'sthumb'=>$_GPC['sthumb'],
					'sdesc'=>$_GPC['sdesc'],
					'surl'=>$_GPC['surl'],
					'rednum'=>$_GPC['rednum'],
					'rednum2'=>$_GPC['rednum2'],
					'video'=>$_GPC['video'],
					'noprize'=>$_GPC['noprize'],
					'prizes'=>serialize($prize),
				);
				if ($id){
					if (pdo_update($this->modulename."_rule",$data,array('id'=>$id)) === false){
						message('编辑活动失败！');
					}else message('编辑活动成功！',$this->createWebUrl('index'));
				}else{
					if (pdo_insert($this->modulename."_rule",$data) === false){
						message('新建活动失败！');
					}else message('新建活动成功！',$this->createWebUrl('index'));
				}
			}
			$item = pdo_fetch('select * from '.tablename($this->modulename."_rule")." where id='{$id}'");
			$awards = unserialize($item['prizes']);
		}elseif ($op == 'list'){
			$list = pdo_fetchall('select *,(select count(1) from '.tablename($this->modulename."_player").' where rid=r.id) attend,(select count(1) from '.tablename($this->modulename."_player").' where rid=r.id and status=1) award from '.tablename($this->modulename."_rule")." r where r.weid='{$_W['uniacid']}'");
		}elseif ($op == 'player'){
			$keyword = $_GPC['keyword'];
			if (!empty($keyword)) $con = " and ( realname like '%{$keyword}%' or mobile like '{$keyword}%')";
			$pindex = max(1, intval($_GPC['page']));
			$psize = 20;
			$list = pdo_fetchall('select * from '.tablename($this->modulename."_player")." where rid='{$id}' {$con} order by id LIMIT " . ($pindex - 1) * $psize . ",{$psize}");
			$total = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename($this->modulename.'_player') . " where rid='{$id}'");
			$pager = pagination($total, $pindex, $psize);
		}elseif ($op == 'award'){
			$keyword = $_GPC['keyword'];
			if (!empty($keyword)) $con = " and ( realname like '%{$keyword}%' or mobile like '{$keyword}%')";
			$pindex = max(1, intval($_GPC['page']));
			$psize = 20;
			$list = pdo_fetchall('select * from '.tablename($this->modulename."_player")." where rid='{$id}' and prize!='' {$con} order by id LIMIT " . ($pindex - 1) * $psize . ",{$psize}");
			$total = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename($this->modulename.'_player') . " where rid='{$id}'");
			$pager = pagination($total, $pindex, $psize);
		}elseif ($op == 'status'){
			if (pdo_update($this->modulename."_player",array('status'=>1),array('id'=>$_GPC['pid'])) === false){
				message('发奖失败');
			}else message('发奖成功!',$this->createWebUrl('index',array('rid'=>$id,'op'=>'player')));
		}elseif ($op == 'dstatus1'){
			if (pdo_update($this->modulename."_player",array('dstatus'=>0),array('id'=>$_GPC['pid'])) === false){
				message('恢复失败');
			}else message('恢复成功!',$this->createWebUrl('index',array('rid'=>$id,'op'=>'player')));
		}elseif ($op == 'dstatus'){
			if (pdo_update($this->modulename."_player",array('dstatus'=>-1),array('id'=>$_GPC['pid'])) === false){
				message('拉入黑名单失败');
			}else message('拉入黑名单成功!',$this->createWebUrl('index',array('rid'=>$id,'op'=>'player')));
		}
		include $this->template('index');
	}
	
	public function doMobileIndex(){
		global $_W,$_GPC;
		$rid = $_GPC['rid'];
		$rule = pdo_fetch('select * from '.tablename($this->modulename."_rule")." where id='{$rid}'");
		$pics = unserialize($rule['pictrues']);
		$info = $this->getInfo();
		$player = pdo_fetch('select * from '.tablename($this->modulename."_player")." where rid='{$rid}' and openid='{$info['openid']}'");
		if (empty($player)){
			pdo_insert($this->modulename."_player",array('rid'=>$rid,'openid'=>$info['openid'],'nickname'=>$info['nickname'],'avatar'=>$info['avatar'],'createtime'=>time()));
			$player['id'] = pdo_insertid();;
		}
		$rank = pdo_fetchcolumn('select count(1) from '.tablename($this->modulename."_player")." where rid='{$rid}' and id<='{$player['id']}'");
		if (empty($player['mobile'])){
			//遍历奖励 查看是否中奖
			$prizes = unserialize($rule['prizes']);
			$prize = '';
			foreach ($prizes as $value) {
				$ps = explode(',', $value['prizerank']);
				if (in_array($rank, $ps)){
					$value['thumb'] = toimage($value['prizethumb']);
					pdo_update($this->modulename."_player",array('prize'=>serialize($value)),array('id'=>$player['id']));
					$prize = $value;
					break;
				}
			}
		}else $prize = unserialize($player['prize']);
		include $this->template('index');
	}
	
	public function doWebExport(){
		global $_GPC;
		include_once 'excel.php';
		$list = pdo_fetchall('select * from '.tablename($this->modulename."_player")." where rid='{$_GPC['rid']}' order by id" );
		$exceler = new Jason_Excel_Export();
		$exceler->charset('UTF-8');
		// 生成excel格式 这里根据后缀名不同而生成不同的格式。jason_excel.csv
		$exceler->setFileName('参与者名单');
		// 设置excel标题行
		$excel_title = array('排名','粉丝昵称','openid','姓名','手机','参与时间');
		$exceler->setTitle($excel_title);
		// 设置excel内容
		$excel_data = array();
		$allsum = 0;
		foreach ($list as $key => $value) {
			$data = array();
			$data[] = $key+1;
			$data[] = $value['nickname'];
			$data[] = $value['openid'];
			$data[] = $value['realname'];
			$data[] = $value['mobile'];
			$data[] = date("Y-m-d H:i:s", $value["createtime"]);
			$excel_data[] = $data;
			$allsum++;
		}
		$excel_data[] = array('总人数:', $allsum);
		$exceler->setContent($excel_data);
		// 生成excel
		$exceler->export();
	}
	
	public function doMobileRed(){
		global $_W,$_GPC;
		$rid = $_GPC['rid'];
		$rule = pdo_fetch('select * from '.tablename($this->modulename."_rule")." where id='{$rid}'");
		if ($rule['starttime'] > time()) message('活动未开始！');
		if ($rule['endtime'] < time()) message('活动已结束！');
		$info = $this->getInfo();
		$player = pdo_fetch('select * from '.tablename($this->modulename."_player")." where rid='{$rid}' and openid='{$info['openid']}'");
		if (empty($player['mobile'])) message('请先报名参与活动！',$this->createMobileUrl('index',array('rid'=>$rid)));
		else{
			if ($player['status'] == -1) message('你已经被列入黑名单，无法领奖！');			
			elseif ($player['rstatus'] == 1) message('你已经领奖！'); 
			elseif (empty($player['rstatus'])) {
				$money = $rule['rednum'];
				if ($rule['rednum2'] > 0) $money = intval(mt_rand($rule['rednum'],$rule['rednum2']));
				if ($this->sendRedPacket($player, $money) === true){
					pdo_update($this->modulename."_player",array('rstatus'=>1),array('id'=>$player['id']));
					message('领奖成功！',$this->createMobileUrl('pic',array('rid'=>$rid)));
				}else message('领奖失败！');
			}
		}
	}
	
	public function doMobilePic(){
		global $_W,$_GPC;
		$rid = $_GPC['rid'];
		$rule = pdo_fetch('select * from '.tablename($this->modulename."_rule")." where id='{$rid}'");
		include $this->template('pic');
	}
	
	public function doMobileInfo(){
		global $_W,$_GPC;
		$rid = $_GPC['rid'];
		$pid = $_GPC['pid'];
		$rule = pdo_fetch('select * from '.tablename($this->modulename."_rule")." where id='{$rid}'");
		
		$name = trim($_GPC['realname']);
		$mobile = trim($_GPC['mobile']);
		if(empty($mobile) || !preg_match("/^1[34578]\d{9}$/",$mobile)){
			die(json_encode(array('errcode'=>-1,'msg'=>'请填写正确的手机号码')));
		}
		if(empty($name)){
			die(json_encode(array('errcode'=>-1,'msg'=>'请填写真实姓名')));
		}
		if (pdo_update($this->modulename."_player",array('realname'=>$name,'mobile'=>$mobile),array('id'=>$pid)) === false){
			die(json_encode(array('errcode'=>-1,'msg'=>'报名失败！')));
		}
		die(json_encode(array('errcode'=>1)));
	}
	
	
	private function getInfo(){
		global $_W;
		$userAgent = $_SERVER['HTTP_USER_AGENT'];
		if (!strpos($userAgent, 'MicroMessenger')) {
			message('请使用微信浏览器打开！');
			return array('openid'=>'oUvXSsv6hNi7wdmd5uWQUTS4vJTY','nickname'=>'junsion');
		}
		load()->model('mc');
		$info = mc_oauth_userinfo();
		return $info;
	}
	
	private function sendRedPacket($player,$money){
		global $_W,$_GPC;
		$url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
		load()->func('communication');
		$pars = array();
		$cfg = $this->module['config'];
		$api = $cfg['api'];
		$activity = $cfg['redpacket'];
		$pars['nonce_str'] = random(32);
		$pars['mch_billno'] = $api['mchid'] . date('Ymd') . sprintf('%010d', $player['id']);
		$pars['mch_id'] = $api['mchid'];
		$pars['wxappid'] = $api['appid'];
		$pars['nick_name'] = $activity['provider'];
		$pars['send_name'] = $activity['provider'];
		$pars['re_openid'] = $player['openid'];
		$pars['total_amount'] = $money;
		$pars['total_num'] = 1;
		$pars['wishing'] = $activity['wish'];
		$pars['client_ip'] = $api['ip'];
		$pars['act_name'] = $activity['title'];
		$pars['remark'] = $activity['remark'];
		ksort($pars, SORT_STRING);
		$string1 = '';
		foreach($pars as $k => $v) {
			$string1 .= "{$k}={$v}&";
		}
		$string1 .= "key={$api['password']}";
		$pars['sign'] = strtoupper(md5($string1));
		$xml = array2xml($pars);
		$extras = array();
		$extras['CURLOPT_CAINFO'] = OD_ROOT . '/cert/'.md5("root{$_W['uniacid']}ca").".pem";
		$extras['CURLOPT_SSLCERT'] = OD_ROOT . '/cert/'.md5("apiclient_{$_W['uniacid']}cert").".pem";
		$extras['CURLOPT_SSLKEY'] = OD_ROOT . '/cert/'.md5("apiclient_{$_W['uniacid']}key").".pem";
		$procResult = false;
		$resp = ihttp_request($url, $xml, $extras);
		if(is_error($resp)) {
			$setting = $this->module['config'];
			$setting['api']['error'] = $resp['message'];
			$this->saveSettings($setting);
			$procResult = $resp['message'];
		} else {
			$xml = '<?xml version="1.0" encoding="utf-8"?>' . $resp['content'];
			$dom = new DOMDocument();
			if($dom->loadXML($xml)) {
				$xpath = new DOMXPath($dom);
				$code = $xpath->evaluate('string(//xml/return_code)');
				$ret = $xpath->evaluate('string(//xml/result_code)');
				if(strtolower($code) == 'success' && strtolower($ret) == 'success') {
					$procResult = true;
					$setting = $this->module['config'];
					$setting['api']['error'] = '';
					$this->saveSettings($setting);
				} else {
					$error = $xpath->evaluate('string(//xml/err_code_des)');
					$setting = $this->module['config'];
					$setting['api']['error'] = $error;
					$this->saveSettings($setting);
					$procResult = $error;
				}
			} else {
				$procResult = 'error response';
			}
		}
		return $procResult;
	}

}